package com.softer.wxzj.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softer.wxzj.common.entity.CommonResult;
import com.softer.wxzj.common.entity.Page;
import com.softer.wxzj.common.enums.NumStrEnum;
import com.softer.wxzj.common.enums.NumberEnum;
import com.softer.wxzj.common.enums.ShiroResultEnum;
import com.softer.wxzj.common.error.CourseException;
import com.softer.wxzj.common.util.ShiroUserUtil;
import com.softer.wxzj.common.util.StringUtils;
import com.softer.wxzj.common.util.UUIDUtil;
import com.softer.wxzj.entity.*;
import com.softer.wxzj.mapper.MaintenanceEquipmentMapper;
import com.softer.wxzj.mapper.MaintenanceObjectMapper;
import com.softer.wxzj.service.MaintenanceEquipmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Gong Zhiyang
 * @date 2019/7/16
 */
@Service
public class MaintenanceEquipmentServiceImpl implements MaintenanceEquipmentService {
    @Autowired
    private MaintenanceEquipmentMapper maintenanceEquipmentMapper;
    @Autowired
    private MaintenanceObjectMapper maintenanceObjectMapper;
    @Autowired
    private FileServiceImpl fileService;

    /**
     * 新增维修设备
     *
     * @param maintenanceEquipment 维修设备
     * @return 新增结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult add(MaintenanceEquipment maintenanceEquipment) {
        checkDate(maintenanceEquipment);
        String userName = maintenanceEquipment.getCreater();
        if (StringUtils.isEmpty(userName)) {
            userName = ShiroUserUtil.getUserName();
            maintenanceEquipment.setCreater(userName);
            maintenanceEquipment.setModifier(userName);
        }
        maintenanceEquipment.setId(UUIDUtil.getUUID());
        maintenanceEquipment.setState(String.valueOf(NumberEnum.ONE.getNum()));
        int num = maintenanceEquipmentMapper.insert(maintenanceEquipment);
        if (num <= 0) {
            return CommonResult.ResponseResult(num);
        }
        //保存图片
        CommonResult commonResult = fileService.addFile(maintenanceEquipment.getFileTypeList(), maintenanceEquipment.getId());
        if (ShiroResultEnum.FAIL.getCode() == commonResult.getData()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), commonResult.getMessage());
        }
        return CommonResult.ResponseResult(num);
    }

    /**
     * 校验日期
     *
     * @param maintenanceEquipment 对象实体
     */
    private void checkDate(MaintenanceEquipment maintenanceEquipment) {
        if (StringUtils.isEmpty(maintenanceEquipment.getAcceptanceDate())) {
            maintenanceEquipment.setAcceptanceDate(null);
        }
    }

    /**
     * 修改维修设备
     *
     * @param maintenanceEquipment 维修设备
     * @return 修改结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult update(MaintenanceEquipment maintenanceEquipment) {
        checkOper(maintenanceEquipment);
        checkDate(maintenanceEquipment);
        int num = maintenanceEquipmentMapper.updateByPrimaryKey(maintenanceEquipment);
        if (num <= 0) {
            return CommonResult.ResponseResult(num);
        }
        //处理图片修改
        CommonResult result = fileService.updateFile(maintenanceEquipment.getFileTypeList(), maintenanceEquipment.getId());
        if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), result.getMessage());
        }
        return CommonResult.ResponseResult(num);
    }

    /**
     * 区别内外网操作人
     *
     * @param maintenanceEquipment 维修对象
     */
    private void checkOper(MaintenanceEquipment maintenanceEquipment) {
        String userName = maintenanceEquipment.getModifier();
        if (StringUtils.isEmpty(userName)) {
            userName = ShiroUserUtil.getUserName();
            maintenanceEquipment.setModifier(userName);
        }
    }

    /**
     * 查询详情
     *
     * @param id      ID
     * @param arcType 图档大类
     * @return 维修设备详情
     */
    @Override
    public MaintenanceEquipment getInfo(String id, String arcType) {
        MaintenanceEquipment maintenanceEquipment = maintenanceEquipmentMapper.selectByPrimaryKey(id);
        //获取父级ID
        String parentId = getParentId(maintenanceEquipment.getMaintenanceObjectId());
        maintenanceEquipment.setMaintenanceObjectId(parentId);
        // 查询图档信息
        List<FileVO> fileVOList = fileService.getFileVOList(id, arcType);
        maintenanceEquipment.setFileTypeList(fileVOList);
        return maintenanceEquipment;
    }

    /**
     * 获取父级ID
     *
     * @param maintenanceObjectId 维修类别ID
     * @return 所有父级ID集合，以逗号分隔
     */
    private String getParentId(String maintenanceObjectId) {

        List<String> list = new ArrayList<>(6);
        list.add(maintenanceObjectId);
        MaintenanceObject maintenanceObject = maintenanceObjectMapper.selectByPrimaryKey(maintenanceObjectId);
        while (!NumStrEnum.ZERO.getNum().equals(maintenanceObject.getParentId())) {
            maintenanceObject = maintenanceObjectMapper.selectByPrimaryKey(maintenanceObject.getParentId());
            list.add(0, maintenanceObject.getId());
        }
        String objectId = String.join(",", list);
        return objectId;
    }

    /**
     * 刪除维修设备
     *
     * @param id ID
     * @return 删除结果
     */
    @Override
    public CommonResult delete(String id) {
        List<String> list = maintenanceEquipmentMapper.checkProject(id);
        if (!list.isEmpty()) {
            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "维修项目中存在该对象，禁止删除");
        }
        return CommonResult.ResponseResult(maintenanceEquipmentMapper.deleteByPrimaryKey(id));
    }

    /**
     * 竣工
     *
     * @param id   自然幢ID
     * @param date 竣工日期
     * @return 操作结果
     */
    @Override
    public CommonResult finish(String id, String date) {
        return CommonResult.ResponseResult(maintenanceEquipmentMapper.finish(id, date, ShiroUserUtil.getUserName()));
    }

    /**
     * 维修对象维护列表
     *
     * @param page           分页实体
     * @param baseRegionInfo 查询实体
     * @return 小区列表
     */
    @Override
    public PageInfo<BaseRegionInfo> getRegionList(Page page, BaseRegionInfo baseRegionInfo) {
        List<BaseRegionInfo> list;
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        if (StringUtils.isNotEmpty(baseRegionInfo.getFuzzy())) {
            //模糊查询
            list = maintenanceEquipmentMapper.fuzzyRegionList(baseRegionInfo.getFuzzy());
        } else {
            //精确查询
            list = maintenanceEquipmentMapper.getRegionList(baseRegionInfo);
        }
        PageInfo<BaseRegionInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 维修对象维护列表
     *
     * @param page          分页实体
     * @param baseBuildInfo 查询实体
     * @return 自然幢列表
     */
    @Override
    public PageInfo<BaseBuildInfo> getBuildList(Page page, BaseBuildInfo baseBuildInfo) {
        List<BaseBuildInfo> list;
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        if (StringUtils.isNotEmpty(baseBuildInfo.getFuzzy())) {
            //模糊查询
            list = maintenanceEquipmentMapper.fuzzyBuildList(baseBuildInfo);
        } else {
            //精确查询
            list = maintenanceEquipmentMapper.getBuildList(baseBuildInfo);
        }
        PageInfo<BaseBuildInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 根据自然幢ID查询公共设施
     *
     * @param page          分页实体
     * @param tempEquipment 查询实体
     * @return 公共设施列表
     */
    @Override
    public PageInfo<TempEquipment> getEquipmentList(Page page, TempEquipment tempEquipment) {
        String objectId = tempEquipment.getObjectId();
        if (StringUtils.isNotEmpty(objectId)) {
            MaintenanceObject maintenanceObject = maintenanceObjectMapper.selectByPrimaryKey(objectId);
            if (String.valueOf(NumberEnum.ZERO.getNum()).equals(maintenanceObject.getParentId())) {
                tempEquipment.setObjectId(null);
            }
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<TempEquipment> list;
        if (StringUtils.isNotEmpty(tempEquipment.getFuzzy())) {
            //模糊查询
            list = maintenanceEquipmentMapper.fuzzyEquipmentList(tempEquipment);
        } else {
            //精确查询
            list = maintenanceEquipmentMapper.getEquipmentList(tempEquipment);
        }
        PageInfo<TempEquipment> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 根据维修对象类别查询维修对象列表
     *
     * @param id 维修对象类别
     * @return 维修对象列表
     */
    @Override
    public List<TempEquipment> getEquipmentListByObjectId(String id) {
        return maintenanceEquipmentMapper.getEquipmentListByObjectId(id);
    }

    /**
     * 启用、停用维修设备
     *
     * @param maintenanceEquipment id    设备ID
     *                             state 状态（0停用，1启用）
     * @return 操作结果
     */
    @Override
    public CommonResult enable(MaintenanceEquipment maintenanceEquipment) {
        checkOper(maintenanceEquipment);
        return CommonResult.ResponseResult(maintenanceEquipmentMapper.updateByPrimaryKeySelective(maintenanceEquipment));
    }

    @Override
    public MaintenanceEquipment getInfoById(String id) {
        return maintenanceEquipmentMapper.getInfoById(id);
    }

    /**
     * 外网查询查询维修对象列表
     *
     * @param page          分页实体
     * @param tempEquipment 查询实体
     * @return 维修对象列表
     */
    @Override
    public PageInfo<TempEquipment> getEquipmentListByOperNo(Page page, TempEquipment tempEquipment) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<TempEquipment> list = maintenanceEquipmentMapper.getEquipmentListByOperNo(tempEquipment);
        for (TempEquipment equipment : list) {
            List<String> useList = maintenanceEquipmentMapper.checkProject(equipment.getId());
            if (!useList.isEmpty()) {
                //删除标志（0不可删，1可删）
                equipment.setDeleteFlag(NumStrEnum.ZERO.getNum());
            }else {
                equipment.setDeleteFlag(NumStrEnum.ONE.getNum());
            }
        }

        return new PageInfo<>(list);
    }

}
